package cn.j0n4than.accountingtool.service.impl;

import cn.j0n4than.accountingtool.entity.Type;
import cn.j0n4than.accountingtool.mapper.TypeMapper;
import cn.j0n4than.accountingtool.service.TypeService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 支出类型服务接口实现
 *
 * @author jonathan
 */
@Service
public class TypeServiceImpl extends ServiceImpl<TypeMapper, Type> implements TypeService {
    /**
     * 获取支出类型列表
     *
     * @param type   Type实例
     * @param userId 用户id
     * @return List
     */
    @Override
    public List<Type> getList(Type type, Integer userId) {
        QueryWrapper<Type> typeQueryWrapper = this.queryConditionals(type, userId);
        return this.baseMapper.selectList(typeQueryWrapper);
    }

    /**
     * 通过ID获取支出类型
     *
     * @param id 支出ID
     * @return Type
     */
    @Override
    public Type getTypeById(Integer id) {
        return this.baseMapper.selectById(id);
    }

    private QueryWrapper<Type> queryConditionals(Type type, Integer userId) {
        QueryWrapper<Type> typeQueryWrapper = new QueryWrapper<>();

        //类型ID
        if (type.id != null) {
            typeQueryWrapper.eq("id", type.id);
        }

        //类型名
        if (type.name != null) {
            typeQueryWrapper.eq("name", type.id);
        }

        //获取自带的类型和这个用户自定义的类型
        if (userId != null) {
            typeQueryWrapper
                    .eq("user_id", userId)
                    .or()
                    .eq("user_id", 0);
        }

        return typeQueryWrapper;
    }
}
